﻿/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 2019-09-08
 * Time: 14:27
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Windows.Forms;

namespace QStarter
{
	/// <summary>
	/// Description of AppHotKey.
	/// </summary>
	public class HotKey
	{
//		组合控制键
//		public enum KeyModifiers { None = 0, Alt = 1, Ctrl = 2, Shift = 4, WindowsKey = 8 }
        
        public static string RegKey(IntPtr hwnd, int keyId, int modifiers, Keys key)
        {
        	string result = string.Empty;
            try
            {
                if (!NativeMethods.RegisterHotKey(hwnd, keyId, modifiers, key))
                {
                	result = "注册热键失败";
//                	result = Marshal.GetLastWin32Error() == 1409 ? "热键被占用" : "注册热键失败";
                }
            }
            catch (Exception) { }
            
            return result;
        }
        
        public static string RegKeyFromString(IntPtr hwnd, int keyId, string keyString)
        {
			string result = "热键格式错误";
			
			if (keyString.Length > 0) 
			{
				string[] modifierskey = keyString.Split('+');
				if (modifierskey.Length == 2)
				{
					int modifiers = 0;
					if (modifierskey[0].Trim() == "Ctrl") { modifiers = 2; }
					else if (modifierskey[0].Trim() == "Alt") { modifiers = 1; }
					else if (modifierskey[0].Trim() == "Shift") { modifiers = 4; }
					
					Keys key = Keys.None;
					if (("0123456789").IndexOf(modifierskey[1].Trim()) == -1)
					{
						key = (Keys)Enum.Parse(typeof(Keys), modifierskey[1].Trim());
					}
					else
					{
						key = (Keys)Enum.Parse(typeof(Keys), "D" + modifierskey[1].Trim());
					}
					
					if (modifiers != 0 && key != Keys.None)
					{
						result = HotKey.RegKey(hwnd, keyId, modifiers, key);
					}
				}
			}
			
			return result;
        	
        }
        
        public static void UnRegKey(IntPtr hwnd, int keyId)
        {
            NativeMethods.UnregisterHotKey(hwnd, keyId);
        }
	}
}
